package TestBigDecimal;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

public class Test {
    public static void main(String[] args) {
        test1();
        test2();
        test3();
        test4();
        test5();
        test6();
    }
    public static void test1() {
        BigDecimal doubleNum1 = new BigDecimal(1.50);
        System.out.println(doubleNum1);
        System.out.println("-------------------");
        BigDecimal doubleNum = new BigDecimal(1.99);
        System.out.println(doubleNum);//将一个四舍五入的值传给了BigDecimal。BigDecimal然后精确地表达了这个不精确的值
        System.out.println("-------------------");
    }
    public static void test2() {
        BigDecimal StringNum = new BigDecimal("1.99");
        System.out.println(StringNum);
        System.out.println("-------------------");
    }
    public static void test3() {
        BigDecimal a = new BigDecimal("1.35");
        BigDecimal b = new BigDecimal("3.21");
        System.out.println(a.add(b));
        System.out.println("-------------------");
        System.out.println(a.subtract(b));
        System.out.println("-------------------");
        System.out.println(a.multiply(b));
        System.out.println("-------------------");
    }
    public static void test4() {
        BigDecimal a = new BigDecimal("1.35");
        BigDecimal b = new BigDecimal("3.21");
        System.out.println(a.divide(b));//发生算数异常，因为除不尽
        System.out.println("-------------------");
    }
    public static void test5() {
        BigDecimal a = new BigDecimal("1.35");
        BigDecimal b = new BigDecimal("3.21");
        //为了可以实现除法，1、可以指定精度和舍入模式
        System.out.println(a.divide(b, 4, RoundingMode.HALF_UP));//保留4位，四舍五入
        System.out.println("-------------------");
        System.out.println(a.divide(b, 4, RoundingMode.CEILING));//保留4位，向正无穷大方向舍入
        //其他舍入模式可以上网自行查找
        System.out.println("-------------------");
    }
    public static void test6() {
        BigDecimal a = new BigDecimal("1.35");
        BigDecimal b = new BigDecimal("3.21");
        System.out.println(a.divide(b, new MathContext(4, RoundingMode.HALF_UP)));//使用MathContext
        System.out.println("-------------------");
        System.out.println(a.divide(b, new MathContext(4)));//没有指定舍入模式，则为RoundingMode.HALF_UP
    }
}
